﻿<%@ Assembly Name="Carbon.Web.Forms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9d724a5d0e74c67c" %>
<%@ Assembly Name="Carbon.Web.Forms.jQueryForms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9d724a5d0e74c67c" %>
<%@ Register TagPrefix="cwf" Namespace="Carbon.Web.Forms" Assembly="Carbon.Web.Forms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9d724a5d0e74c67c" %>
<%@ Register TagPrefix="cwfj" Namespace="Carbon.Web.Forms.jQueryForms" Assembly="Carbon.Web.Forms.jQueryForms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9d724a5d0e74c67c" %>
<%@ Register TagPrefix="ufe" Namespace="Carbon.Web.Forms.jQueryForms.DataEditors.UploadEditor"
    Assembly="Carbon.Web.Forms.jQueryForms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=9d724a5d0e74c67c" %>
<%@ Import Namespace="Carbon.Web.Forms.jQueryForms" %>

<%@ Page Language="C#" Inherits="Carbon.Web.Forms.jQueryForms.DataEditors.UploadEditor.UploadEditorPopup" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="<%# jQueryFormsConfiguration.ServerRelativeBaseCssUrl %>" rel="stylesheet"
        type="text/css" />
    <link href="<%# jQueryFormsConfiguration.ServerRelativeSkinCssUrl %>" rel="stylesheet"
        type="text/css" />
</head>
<body>
    <form runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <cwfj:environmentcontrol runat="server" />
    <style type="text/css">
        form
        {
            font-size: 12px;
            padding: 10px;
        }
        
        .carbon-close
        {
            float: right;
            width: 16px;
            height: 16px;
        }
        .carbon-file
        {
            display: inline-block;
            width: 260px;
            margin-bottom: 5px;
            padding: 5px;
        }
        .carbon-content
        {
            font-weight: bold;
            overflow: hidden;
            display: inline-block;
            width: 234px;
            padding-bottom: 5px;
        }
        .carbon-state
        {
        }
    </style>
    <ufe:UploadEditorPopupDataContextControl runat="server" ID="ctrl_Popup">
      <style type="text/css">
          .carbon-close
          {
              float: right;
              width: 16px;
              height: 16px;
          }
          .carbon-file
          {
              display: inline-block;
              width: 260px;
              margin-bottom: 5px;
              padding: 5px;
          }
          .carbon-content
          {
              font-weight: bold;
              overflow: hidden;
              display: inline-block;
              width: 234px;
              padding-bottom: 5px;
          }
          .carbon-state
          {
          }
      </style>
    <div id="upload">
        <div class="carbon-files">
            <div class="carbon-files-upload-error ui-state-error-text" style="display: none;">
                <span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
                <span class="carbon-error-text"></span>
            </div>
            <div class="carbon-file ui-widget-content ui-corner-all" style="display: none;">
                <div class="carbon-content">
                </div>
                <div class="carbon-close ui-state-default ui-corner-all">
                    <span class="ui-icon ui-icon-circle-close">&nbsp;</span>
                </div>
                <div class="carbon-upload-state">
                    
                </div>
                <iframe style='display: none;'></iframe>
            </div>
        </div>
        <input type="button" class="carbon-files-add" value='<%# Resources.GetString("UploadFiles.Add")  %>' />
        <input type="button" class="carbon-files-upload" value='<%# Resources.GetString("UploadFiles.Upload")  %>' style="display:none;" />
        <asp:TextBox class="carbon-state" runat="server" style="display:none;" ID="ctrl_Files" />
    </div>
    <script type="text/javascript">

        (function ($) {

            var Constants = {
                HandlerPath: "/.jQueryFormsUi/upload.html"
            };

            var States = {
                WaitForFirstLoad: 0,
                FirstTimeLoaded: 1,
                WaitForUpload: 2,
                Uploaded: 3,
                Error: 4,
                Deleting: 5
            };

            var Classes = {
                LoaderClass: "carbon-loader",
                ErrorText: "carbon-error-text"
            };

            var jqforms = Carbon.Web.Forms.jQueryForms;

            var singleChild = function (target, selector) {
                var result = target.find(selector);
                if (result.length != 1)
                    throw "'" + selector + "' not found.";
                return result;
            };

            var endsWithCaseInsensitive = function (val, end) {
                return val.length >= end.length &&
                       val.substr(val.length - end.length).toLowerCase() == end.toLowerCase();
            };

            UploadFilesEditor = function (id, maxNumberOfFiles, fileTypes) {
                var control = $("#" + id);

                control.filesRepeater = singleChild(control, ".carbon-files");

                control.add = singleChild(control, ".carbon-files-add");
                control.add.button();

                control.upload = singleChild(control, ".carbon-files-upload");
                control.upload.button();

                control.state = singleChild(control, ".carbon-state");

                var filesUploadError = singleChild(control, ".carbon-files-upload-error");

                control.add.enable = function (enabled) {
                    if (enabled) {
                        control.add.button("enable");
                    }
                    else {
                        control.add.button("disable");
                    }
                };

                var fileTypesArray = [];

                if (fileTypesArray && fileTypesArray !== "") {
                    fileTypesArray = fileTypes.split(";");

                    for (var i in fileTypesArray) {
                        var elem = $.trim(fileTypesArray[i]).toLowerCase();
                        fileTypesArray[i] = elem;
                    }
                }

                var endsWithCorrectExtension = function (filename) {
                    for (var i in fileTypesArray) {
                        var type = fileTypesArray[i];

                        if (endsWithCaseInsensitive(filename, type)) {
                            return true;
                        }
                    }

                    return false;
                };

                control.template = singleChild(control.filesRepeater, ".carbon-file");

                control.foreachFile = function (doWhat) {
                    control.filesRepeater.children().each(function (key, elem) {
                        var data = $(elem).data("data");
                        if (data && (data.State === States.WaitForUpload || data.State == States.Uploaded)) {
                            doWhat(control, data);
                        }
                    });
                };

                var uploadRequired = false;

                control.checkState = function () {
                    var canUpload = true;

                    var descriptors = [];
                    var values = [];

                    control.foreachFile(function (control, elem) {
                        if (elem.State != States.Uploaded) {
                            canUpload = false;
                        }
                        else {
                            descriptors.push({ id: elem.data("id"), key: elem.data("key"), filename: elem.data("filename") });

                            values.push(elem.data("id"));
                            values.push(elem.data("key"));
                            values.push(elem.data("filename"));
                        }
                    });

                    if (descriptors.length > 0) {
                        control.upload.show();
                    }
                    else {
                        control.upload.hide();
                    }

                    if (descriptors.length < maxNumberOfFiles) {
                        control.add.show();
                    }
                    else {
                        control.add.hide();
                    }

                    if (canUpload && uploadRequired) {
                        control.state.val(Sys.Serialization.JavaScriptSerializer.serialize(values));
                        __doPostBack('', '');
                    }
                };

                control.prepareNew = function () {
                    control.add.enable(false);

                    var prepareElement = control.template.clone();

                    prepareElement.data("data", prepareElement);

                    var iframe = singleChild(prepareElement, "iframe");
                    var content = singleChild(prepareElement, ".carbon-content");
                    var close = singleChild(prepareElement, ".carbon-close");
                    var state = singleChild(prepareElement, ".carbon-upload-state");

                    prepareElement.State = States.WaitForFirstLoad;

                    var displayError = function (error) {
                        state.children().remove();
                        var errorHtml = filesUploadError.clone();
                        errorHtml.show();
                        state.append(errorHtml);
                        singleChild(state, "." + Classes.ErrorText).html(error);
                    };

                    iframe.bind('load', function () {
                        if (prepareElement.State == States.WaitForFirstLoad) {
                            var uploadControl = singleChild(iframe.contents(), "#upload");

                            var form = singleChild(iframe.contents(), "form");

                            form.attr("action", Constants.HandlerPath);

                            prepareElement.select = function () {
                                uploadControl.click();
                            };

                            prepareElement.upload = function () {
                                form.submit();
                            }

                            uploadControl.change(function () {
                                var filename = uploadControl.val();

                                if (filename.lastIndexOf("\\") >= 0) {
                                    filename = filename.substr(filename.lastIndexOf("\\") + 1);
                                }

                                if (filename.lastIndexOf("/") >= 0) {
                                    filename = filename.substr(filename.lastIndexOf("/") + 1);
                                }

                                content.html(filename);
                                prepareElement.State = States.WaitForUpload;

                                prepareElement.data("filename", filename);

                                if (endsWithCorrectExtension(filename)) {
                                    form.submit();
                                    state.children().remove();
                                    state.append($("<img class='" + Classes.LoaderClass + "' src='" + jqforms.Configuration.FilesPath + '/' + jqforms.Resources["Url.Loader"] + "' />"));
                                }
                                else {
                                    prepareElement.State = States.Error;
                                    displayError(jqforms.Resources["UploadFiles.Error.InvalidExtension"]);
                                }

                                prepareElement.css("display", "block");

                                control.prepareNew();
                            });

                            close.hover(function () {
                                $(this).addClass("ui-state-hover");
                            },
                            function () {
                                $(this).removeClass("ui-state-hover");
                            });

                            close.click(function () {
                                if (prepareElement.State == States.Uploaded) {
                                    var form = singleChild(iframe.contents(), "form");
                                    var command = singleChild(iframe.contents(), "#command");

                                    form.attr("action", Constants.HandlerPath);
                                    command.val("Delete");

                                    prepareElement.hide();
                                    prepareElement.State = States.Deleting;
                                    form.submit();
                                    control.checkState();
                                }
                                else {
                                    prepareElement.remove();
                                    control.checkState();
                                }
                            });

                            control.add.enable(true);
                            prepareElement.State = States.FirstTimeLoaded;

                            control.checkState();
                        }
                        else if (prepareElement.State == States.Deleting) {
                            prepareElement.remove();
                        }
                        else if (prepareElement.State == States.WaitForUpload) {
                            state.html("<span class=\"ui-icon ui-icon-circle-check\"></span>");

                            var error = iframe.contents().find("#error");

                            if (error.length == 0) {
                                var key = singleChild(iframe.contents(), "#key");
                                var id = singleChild(iframe.contents(), "#id");
                                prepareElement.data("key", key.val());
                                prepareElement.data("id", id.val());
                                prepareElement.State = States.Uploaded;
                                control.checkState();
                            }
                            else {
                                prepareElement.data("error", error.val());
                                displayError(prepareElement.data("error"));
                                prepareElement.State = States.Error;
                                control.checkState();
                            }
                        }
                    });

                    iframe.attr('src', Constants.HandlerPath);
                    control.filesRepeater.append(prepareElement);

                    control.prepare = prepareElement;
                };

                control.add.click(function () {
                    control.prepare.select();
                });

                control.upload.click(function () {
                    control.add.hide();
                    control.upload.hide();
                    uploadRequired = true;
                    control.checkState();
                });

                control.prepareNew();
            };

        })(jQuery);

        UploadFilesEditor("upload", <%# this.MaxFiles %>, "<%# this.AllowedExtensions %>");

    </script>

    </ufe:UploadEditorPopupDataContextControl>
    </form>
</body>
</html>
